import {
  AUTHORIZATION, 
  COMPANY_QUESTION, 
  ENV,
  QUESTION,
} from "../const/cacheEnum"; 

interface IStorage {
  setItem: (key: string, value: string) => void;
  getItem: <T>(key: string) => T;
  removeItem: (key: string) => void;
  clear: () => void;
}
const TaroStorageAdapter: IStorage = {
  setItem(key: string, value: string) {
    uni.setStorageSync(key, value);
  },
  getItem<T>(key: string) {
    return uni.getStorageSync(key) as unknown as T;
  },
  removeItem(key: string) {
    uni.removeStorageSync(key);
  },
  clear() {
    uni.clearStorageSync();
  },
};

/**
 * @description 封装本地缓存工具方法
 * @author created by 孔东
 * @date 2023-07-14 14:23:25
 * @class LocalCache
 * @returns LocalCache
 */
export class LocalCache<T = unknown> {
  // 缓存的key
  name: string;
  // 缓存管理器
  manager: IStorage;

  defaultValue: T | undefined;

  constructor(name: string, defaultValue?: T, manager?: IStorage) {
    this.name = name;
    this.manager = manager || TaroStorageAdapter;
    this.defaultValue = defaultValue;
  }
  set(value: T) {
    let valueText = "";
    if ((value !== null || value !== undefined) && typeof value !== "string") {
      valueText = JSON.stringify(value);
    }
    if (typeof value === "string") {
      valueText = value;
    }
    this.manager.setItem(this.name, valueText);
  }
  get<T>(noReturnDefaultValue: boolean = false): T | null {
    const value = this.manager.getItem<string>(this.name);
    if(!value) {
      return noReturnDefaultValue ? null : (this.defaultValue as T);
    }
    try {
      if (value !== null && value !== undefined) {
        return JSON.parse(value);
      }
      return noReturnDefaultValue ? null : (this.defaultValue as T);
    } catch (error) {
      return (value as unknown) as T;
    }
  }
  remove() {
    this.manager.removeItem(this.name);
  }
}

export const CacheAuthrizedToken = new LocalCache<string>(AUTHORIZATION);
export const CacheEnv = new LocalCache<string>(ENV);
export const CacheQuestion = new LocalCache<Array<string>>(QUESTION, []);
export const CacheCompanyQuestion = new LocalCache<Array<string>>(COMPANY_QUESTION, []);